package com.gpoint.rdp.door.permissionPid.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gpoint.rdp.base.core.util.string.StringUtil;
import com.gpoint.rdp.base.core.entity.ResultMessage;
import com.gpoint.rdp.base.framework.page.PageList;
import com.gpoint.rdp.base.framework.page.PageResult;
import com.gpoint.rdp.api.base.query.QueryFilter;
import com.gpoint.rdp.base.web.controller.GenericController;
import com.gpoint.rdp.base.web.json.PageJson;
import com.gpoint.rdp.base.web.util.RequestUtil;
import com.gpoint.rdp.common.DoorConfig;
import com.gpoint.rdp.door.permissionPid.service.DoorPermissionPidService;
import com.gpoint.rdp.door.user.persistence.dao.CampusCardQueryDao;
import com.gpoint.rdp.door.user.persistence.entity.CampusCardPo;
import com.gpoint.rdp.door.user.service.CampusCardQueryService;
import com.gpoint.rdp.door.permissionPid.service.DoorPermissionPidQueryService;
import com.gpoint.rdp.door.CurrentPermission.controller.Descartes;
import com.gpoint.rdp.door.CurrentPermission.controller.PreParam;
import com.gpoint.rdp.door.CurrentPermission.persistence.dao.CurrentPermissionQueryDao;
import com.gpoint.rdp.door.CurrentPermission.persistence.entity.CurrentPermissionPo;
import com.gpoint.rdp.door.CurrentPermission.repository.CurrentPermissionRepository;
import com.gpoint.rdp.door.CurrentPermissionHis.persistence.entity.CurrentPermissionHisPo;
import com.gpoint.rdp.door.campusPid.persistence.dao.CampusPidQueryDao;
import com.gpoint.rdp.door.campusPid.persistence.entity.CampusPidPo;
import com.gpoint.rdp.door.campusPid.service.CampusPidQueryService;
import com.gpoint.rdp.door.doorpPermissionPidHis.persistence.entity.PermissionPidHisPo;
import com.gpoint.rdp.door.doorpPermissionPidHis.repository.PermissionPidHisRepository;
import com.gpoint.rdp.door.permissionPid.persistence.dao.DoorPermissionPidQueryDao;
import com.gpoint.rdp.door.permissionPid.persistence.entity.DoorPermissionPidPo;
import com.gpoint.rdp.door.permissionPid.repository.DoorPermissionPidRepository;
import com.gpoint.rdp.base.core.util.AppUtil;
import com.gpoint.rdp.base.core.util.BeanUtils;
import com.gpoint.rdp.base.core.util.JacksonUtil;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// TODO: Auto-generated Javadoc
/**
 * 身份授权表 控制类
 *
 * <pre>
 *  
 * 开发公司：苏州东大金点信息技术有限公司
 * 开发人员：唐红锋
 * 邮箱地址：55872655@qq.com
 * 创建时间：2019-11-27 14:53:17
 * </pre>
 */
@Controller
@RequestMapping("/rdp/permissionPid/doorPermissionPid/")
public class DoorPermissionPidController extends GenericController {

	/** The door permission pid service. */
	@Resource
	private DoorPermissionPidService doorPermissionPidService;

	/** The door permission pid query service. */
	@Resource
	private DoorPermissionPidQueryService doorPermissionPidQueryService;

//	/** The door permission pid query dao. */
//	@Resource
//	private DoorPermissionPidQueryDao doorPermissionPidQueryDao;

	/** The config. */
	DoorConfig config = AppUtil.getBean(DoorConfig.class);

	/** The servicecode. */
	String servicecode = config.getServicecode();

	/** The door permission pid repository. */
//	@Resource
//	private DoorPermissionPidRepository doorPermissionPidRepository;

	/** The permission pid his po repository. */
//	@Resource
//	private PermissionPidHisRepository permissionPidHisPoRepository;

	/** The current permission repository. */
//	@Resource
//	private CurrentPermissionRepository currentPermissionRepository;

	/** The campus card query service. */
	@Resource
	private CampusCardQueryService campusCardQueryService;

	/** The current permission query dao. */
//	@Resource
//	private CurrentPermissionQueryDao currentPermissionQueryDao;

	/** The campus card query dao. */
//	@Resource
//	private CampusCardQueryDao campusCardQueryDao;
//
//	/** The campus pid query dao. */
//	@Resource
//	private CampusPidQueryDao campusPidQueryDao;

	
	/** The campus pid query service. */
	@Resource
	private CampusPidQueryService campusPidQueryService;
	
	
	/**
	 * List. pid auth view.
	 *
	 * @param request  the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = getAutoView();
		return mv;

	}

	/**
	 * Filter char.
	 *
	 * @param userArr the user arr
	 * @return the list
	 */
	private List<String> filterChar(List<String> userArr) {
		String str;
		List<String> userArrs = new ArrayList<String>();
		for (int i = 0; i < userArr.size(); i++) {
			str = userArr.get(i);
			if (str.contains("|")) {
				str = str.substring(0, str.length() - 1);
			}
			userArrs.add(str);
		}
		return userArrs;
	}

	/**
	 * Query.
	 *
	 * @param pararm   the pararm
	 * @param request  the request
	 * @param response the response
	 * @throws Exception the exception
	 */
	@RequestMapping("query")
	public void query(@RequestBody PreParam pararm, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ResultMessage message = null;
		// 过滤 特殊符号
		StringBuffer sb = new StringBuffer();
		try {
			// 获取身份信息
			List<String> userArr = pararm.getUseArr();
			// 获取門
			List<String> doorArr = pararm.getDoorArr();
			List<String> doorArrs = filterChar(doorArr);

			
			// 門和用戶
		    List<List<String>> dimvalue = new ArrayList<List<String>>();
						
						
			List<String> userArrs = filterChar(userArr);
			// 封装为2个List
			List<String> idArrs = new ArrayList<String>();
			//一条字符串变成字符数组
			String[] arr = userArrs.get(0).split(","); 
			for (int i = 0; i < arr.length; i++) {
				idArrs.add(arr[i]);
			}
			dimvalue.add(idArrs);
			dimvalue.add(doorArrs);
			List<String> result = new ArrayList<String>();
			Descartes.run(dimvalue, result, 0, "");

			for (String s : result) {
				// 解析字符串
				String[] record = s.split(",");
				// 用户ID存在- 号 出现异常：
				String pid = record[0].split("-")[0]; 

				String doorno = record[1];
				// 根据uid,和doono 查询，该纪录是否存在，存在则提示终止操作，否则插入
				if (pid == null || doorno == null) {
					message = new ResultMessage(ResultMessage.ERROR, "数据不合法");
					writeResultMessage(response.getWriter(), message);
					return;
				}
				Map<String, String> hashmap = new HashMap<String, String>(256);
				hashmap.put("doorno", doorno);
				hashmap.put("pid", pid);

				
				List<DoorPermissionPidPo> list =  this.doorPermissionPidQueryService.queryByPidAndDoor(hashmap);
				
				if (BeanUtils.isEmpty(list)) {
					continue;
				} else { //
					String doorname = null;
					 String pname=null;
					// 遍历出List
					for (int i = 0; i < list.size(); i++) {
						pid = list.get(i).getPid();
						 List<CampusPidPo> polist = this.campusPidQueryService.getPnameByPid(pid);
						 if (!polist.isEmpty()) {
							    pname = polist.get(0).getPidname();
						   }
						   
						doorname = list.get(i).getControllerno();
						sb.append("身份名称：" + pname + "\t" + "门名称：" + doorname).append("\n<br/>");
					}

				}
			}

			if (StringUtil.isNotEmpty(sb.toString())) {
				sb.append("记录已经存在\n");
			}

		} catch (Exception e) {
			message = new ResultMessage(ResultMessage.ERROR, "操作失败" + e.getMessage());
			logger.error("对TB_DOOR_CURRENTPERMISSION操作失败，" + e.getMessage(), e);
		}

		if (sb.toString().length() > 0) {
			message = new ResultMessage(ResultMessage.SUCCESS, sb.toString());
		} else {
			message = new ResultMessage(ResultMessage.FAIL, sb.toString());
		}
		writeResultMessage(response.getWriter(), message);
	}

	/**
	 * Save to 身份表中，插入是0，待分配，当用户分配完成，通知成功后，通知前端。 batch insert 1 state flag.
	 *
	 * @param pararm   the pararm
	 * @param request  the request
	 * @param response the response
	 * @throws Exception the exception
	 */
	@RequestMapping("save3")
	public void save3(@RequestBody PreParam pararm, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ResultMessage message = null;
		try {
			// 获取数值
			List<String> userArr = pararm.getUseArr();
			String timeseqment = pararm.getStr();

			List<String> doorArr = pararm.getDoorArr();
			List<String> doorArrs = filterChar(doorArr);

			// 过滤 特殊符号
			String startTime = pararm.getStartTime();
			String endTime = pararm.getEndTime();

			List<String> userArrs = filterChar(userArr);
			List<String> idArrs = new ArrayList<String>();
			String[] arr = userArrs.get(0).split(",");
			for (int i = 0; i < arr.length; i++) {
				idArrs.add(arr[i]);
			}

			List<List<String>> dimvalue = new ArrayList<List<String>>();
			dimvalue.add(idArrs);
			dimvalue.add(doorArrs);
			List<String> result = new ArrayList<String>();
			Descartes.run(dimvalue, result, 0, "");
			String pidnmame = null;
			for (String s : result) {
				String[] record = s.split(",");
				String pid = record[0];
				String doorno = record[1]; // 两者不一样的地方，Cur在于关联取出，现在这个前台直接传输
				String doorname = record[2];
				// 当前时间
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
				String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳

				// 组装bean
				DoorPermissionPidPo doorPermissionPidPo = new DoorPermissionPidPo();
				doorPermissionPidPo.setPid(pid);

				// 这里根据tb_zhgx_campus_pid 进行查询，返回name字段并插入：
				//List<CampusPidPo> pidlist = this.campusPidQueryDao.findByKey("getByPid", pid);
				       
				List<CampusPidPo> pidlist =  this.campusPidQueryService.getPnameByPid(pid);
				
				if (pidlist.size() == 1) {
					pidnmame = pidlist.get(0).getPidname();
				} else {
				}
				doorPermissionPidPo.setPidnmame(pidnmame);
				doorPermissionPidPo.setDoorno(doorno);
				doorPermissionPidPo.setControllerno(doorname);
				doorPermissionPidPo.setDeleteflag(0L);
				doorPermissionPidPo.setAllocatedtime(Utils.string2Date(date)); // 插入当前时间戳 date2String
				doorPermissionPidPo.setServicecode(servicecode);
				doorPermissionPidPo.setExt1("");
				doorPermissionPidPo.setExt2("");
				doorPermissionPidPo.setExt3("");
				doorPermissionPidPo.setExt4("");
				doorPermissionPidPo.setExt5("");
				doorPermissionPidPo.setExt6("");
				doorPermissionPidPo.setDowntime(null);
				if(timeseqment==null) {
					timeseqment="1";
				}
				doorPermissionPidPo.setTimeseg(timeseqment);
				doorPermissionPidPo.setStarttime(Utils.string2Date2(startTime));
				doorPermissionPidPo.setEndtime(Utils.string2Date2(endTime));
				
				
				this.doorPermissionPidService.create(doorPermissionPidPo);
//				doorPermissionPidRepository.newInstance(doorPermissionPidPo).create();
				message = new ResultMessage(ResultMessage.SUCCESS, "对TB_DOOR_CURRENTPERMISSION操作成功");
			}

		} catch (Exception e) {
			message = new ResultMessage(ResultMessage.FAIL, "对TB_DOOR_CURRENTPERMISSION操作失败," + e.getMessage());
			logger.error("对TB_DOOR_CURRENTPERMISSION操作失败，" + e.getMessage(), e);
		}
		writeResultMessage(response.getWriter(), message);
	}

	/**
	 * Updaterecord. 先删除原先的记录， 直接新的 插入记录就可以了。
	 *
	 * @param pararm   the pararm
	 * @param request  the request
	 * @param response the response
	 * @throws Exception the exception
	 */
	@RequestMapping("updaterecord")
	public void updaterecord(@RequestBody PreParam pararm, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
//		ResultMessage message = null;
		try {
			List<String> userArr = pararm.getUseArr();
			List<String> doorArr = pararm.getDoorArr();
			List<String> doorArrs = filterChar(doorArr);
			List<String> userArrs = filterChar(userArr);
			List<List<String>> dimvalue = new ArrayList<List<String>>();
			// 封装为2个List
			List<String> idArrs = new ArrayList<String>();
			String[] arr = userArrs.get(0).split(","); //一条字符串变成字符数组
			for (int i = 0; i < arr.length; i++) {
				idArrs.add(arr[i]);
			}
			dimvalue.add(idArrs);
			dimvalue.add(doorArrs);
			List<String> result = new ArrayList<String>();
			Descartes.run(dimvalue, result, 0, "");

			//删除单条记录
			for (String s : result) {
				String[] record = s.split(",");
				String pid = record[0];
				String doorno = record[1];
				Map<String, String> hashmap = new HashMap<String, String>(256);
				hashmap.put("doorno", doorno);
				hashmap.put("pid", pid);
				List<DoorPermissionPidPo> list =  this.doorPermissionPidQueryService.queryByPidAndDoor(hashmap);
				
				if (list.size() == 0) {
				} else { // 单条删除
					String[] ids = new String[1];
					ids[0] = list.get(0).getId();
					doorPermissionPidService.deleteByIds(ids);
				}
			}
		} catch (Exception e) {
			logger.error("对doorPermissionPid操作失败，" + e.getMessage(), e);
		}
		this.save3(pararm, request, response);
	}

	

	/**
	 * cancel teacher auth. 
	 *  first update curent_tab
	 *  sec   update tb_permission_tab;
	 * state change batch 2
	 *
	 * @param request  the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("edit2")
	public ModelAndView edit2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String preUrl = RequestUtil.getPrePage(request);
		// 1.点击取消按钮 更新记录
		// String id=RequestUtil.getString(request, "id");
		String[] ids = RequestUtil.getStringAryByStr(request, "id");
		DoorPermissionPidPo doorPermissionPidPo = null;
		for (int i = 0; i < ids.length; i++) {
			if (StringUtil.isNotEmpty(ids[i])) {
				String data = null;
				// 查询字段数值
				data = doorPermissionPidQueryService.get(ids[i]);
				doorPermissionPidPo = DoorPermissionPidPo.fromJsonString(data);
				// 设置更新字段
				doorPermissionPidPo.setDeleteflag(2L);
				// 清空信息，设置下发时间为空
				doorPermissionPidPo.setAllocatedtime(new Date());
				// 更新数据
//				doorPermissionPidRepository.newInstance(doorPermissionPidPo).update();
                this.doorPermissionPidService.update(doorPermissionPidPo);
				

			}
			
		}
		String jspPath = "/rdp/permissionPid/doorPermissionPidList.jsp";

		return new ModelAndView(jspPath);
	}

	/**
	 * 【身份授权表】列表(分页条件查询)数据.
	 *
	 * @param request the request
	 * @param reponse the reponse
	 * @return the page json
	 * @throws Exception the exception
	 */
	@RequestMapping("listJson")
	public @ResponseBody PageJson listJson(HttpServletRequest request, HttpServletResponse reponse) throws Exception {
		QueryFilter queryFilter = getQuerFilter(request);
		try {

			String begindate = RequestUtil.getString(request, "Q^ALLOCATEDTIME^DL");
			String enddate = RequestUtil.getString(request, "Q^ALLOCATEDTIME^DG");
			// 拼凑SQL：
			if (begindate.length() != 0 && enddate.length() != 0) {
				String sql = "ALLOCATEDTIME >=  to_date('" + begindate + "', 'yyyy-mm-dd hh24:mi:ss')"
						+ "and ALLOCATEDTIME <=  to_date('" + enddate + "', 'yyyy-mm-dd hh24:mi:ss')";
				 queryFilter.addParamsFilter("begin_ALLOCATEDTIME", Utils.string2Date(begindate));
				 queryFilter.addParamsFilter("end_ALLOCATEDTIME", Utils.string2Date(enddate));
				queryFilter.addParamsFilter("whereSql", sql);
			}

			//
			if (begindate.length() != 0 && enddate.length() == 0) {
				String sql = "ALLOCATEDTIME >=   to_date('" + begindate + "', 'yyyy-mm-dd hh24:mi:ss')";
				 queryFilter.addParamsFilter("begin_ALLOCATEDTIME", Utils.string2Date(begindate));
				queryFilter.addParamsFilter("whereSql", sql);
			}

			//
			if (begindate.length() == 0 && enddate.length() != 0) {
				String sql = "ALLOCATEDTIME <=   to_date('" + enddate + "', 'yyyy-mm-dd hh24:mi:ss')";
				 queryFilter.addParamsFilter("end_ALLOCATEDTIME", Utils.string2Date(enddate));
				queryFilter.addParamsFilter("whereSql", sql);
			}

			// 都是空的 直接查出全部

			String listData = doorPermissionPidQueryService.query(queryFilter);
			PageList<DoorPermissionPidPo> doorPermissionPidList = null;
			if (JacksonUtil.isJsonObject(listData)) {
				List<DoorPermissionPidPo> list = DoorPermissionPidPo
						.fromJsonArrayString(JacksonUtil.getString(listData, "data"));
				PageResult pageResult = PageResult.fromJson(JacksonUtil.getString(listData, "pageResult"));
				doorPermissionPidList = new PageList<DoorPermissionPidPo>(list, pageResult);
			}

			return new PageJson(doorPermissionPidList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new PageJson();
		}
	}

	/**
	 * 编辑【身份授权表】信息页面.
	 *
	 * @param request  the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("edit")
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String preUrl = RequestUtil.getPrePage(request);
		String id = RequestUtil.getString(request, "id");
		DoorPermissionPidPo doorPermissionPid = null;
		if (StringUtil.isNotEmpty(id)) {
			String data = null;
			data = doorPermissionPidQueryService.get(id);
			doorPermissionPid = DoorPermissionPidPo.fromJsonString(data);
		}

		return getAutoView().addObject("doorPermissionPid", doorPermissionPid).addObject("returnUrl", preUrl);
	}

	/**
	 * 编辑【身份授权表】信息页面.
	 *
	 * @param request  the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("flowEdit")
	public ModelAndView flowEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String preUrl = RequestUtil.getPrePage(request);
		String id = RequestUtil.getString(request, "id");
		DoorPermissionPidPo doorPermissionPid = null;
		if (StringUtil.isNotEmpty(id)) {
			String data = null;
			data = doorPermissionPidQueryService.get(id);
			doorPermissionPid = DoorPermissionPidPo.fromJsonString(data);
		}
		return getAutoView().addObject("doorPermissionPid", doorPermissionPid).addObject("returnUrl", preUrl);
	}

	/**
	 * 【身份授权表】明细页面.
	 *
	 * @param request  the request
	 * @param response the response
	 * @return the model and view
	 * @throws Exception the exception
	 */
	@RequestMapping("get")
	public ModelAndView get(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String preUrl = RequestUtil.getPrePage(request);
		String id = RequestUtil.getString(request, "id");
		DoorPermissionPidPo doorPermissionPid = null;
		if (StringUtil.isNotEmpty(id)) {
			String data = null;
			data = doorPermissionPidQueryService.get(id);
			doorPermissionPid = DoorPermissionPidPo.fromJsonString(data);
		}
		return getAutoView().addObject("doorPermissionPid", doorPermissionPid).addObject("returnUrl", preUrl);
	}

	/**
	 * 
	 * 保存【身份授权表】信息.
	 *
	 * @param request  the request
	 * @param response the response
	 * @throws Exception the exception
	 */
	@RequestMapping("save")
	public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResultMessage message = null;
		try {
			String json = RequestUtil.getString(request, "json");
			doorPermissionPidService.save(json);
			message = new ResultMessage(ResultMessage.SUCCESS, "保存身份授权表成功");
		} catch (Exception e) {
			message = new ResultMessage(ResultMessage.FAIL, "对身份授权表操作失败," + e.getMessage());
			logger.error("对身份授权表操作失败，" + e.getMessage(), e);
		}
		writeResultMessage(response.getWriter(), message);
	}

	/**
	 * 批量删除【身份授权表】记录.
	 *
	 * @param request  the request
	 * @param response the response
	 * @throws Exception the exception
	 */
	@RequestMapping("remove")
	public void remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ResultMessage message = null;
		try {
			// 获得待删除的id
			String[] ids = RequestUtil.getStringAryByStr(request, "id");
			doorPermissionPidService.deleteByIds(ids);
			message = new ResultMessage(ResultMessage.SUCCESS, "删除身份授权表成功");
		} catch (Exception e) {
			message = new ResultMessage(ResultMessage.FAIL, "删除身份授权表失败，" + e.getMessage());
			logger.error("删除身份授权表失败，" + e.getMessage(), e);
		}
		writeResultMessage(response.getWriter(), message);
	}

}